package com.josework.springhelloworld.dao;

import com.josework.springhelloworld.model.Article;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: Joseph Xu
 * @Date: 2021/7/24 20:22
 */
@Slf4j
@Repository
public class ArticleJDBCDao {

    @Autowired
    private JdbcTemplate primaryJdbcTemplate;

    @Autowired
    private JdbcTemplate secondaryJdbcTemplate;


    //保存文章
    public int save(Article article,JdbcTemplate jdbcTemplate){

        if (jdbcTemplate == null){
            jdbcTemplate = primaryJdbcTemplate;
        }
        int res = jdbcTemplate.update("INSERT INTO topair.article\n" +
                        "(author, title, content, create_time) values(?,?,?,?)",
                article.getAuthor(),
                article.getTitle(),
                article.getContent(),
                article.getCreateTime());

        return  res;

    }

    //删除文章
    public  int deleteById(Article article,JdbcTemplate jdbcTemplate){
        if(jdbcTemplate == null){
            jdbcTemplate = primaryJdbcTemplate;
        }
        return jdbcTemplate.update("delete from article where id = ?",article.getId());
    }

    //更新文章
    public int updateById(Article article,JdbcTemplate jdbcTemplate){
        if(jdbcTemplate == null){
            jdbcTemplate = primaryJdbcTemplate;
        }
        return jdbcTemplate.update("update article set author = ?,title= ?,content = ?,create_time = ? where id = ?",
                article.getAuthor(),
                article.getTitle(),
                article.getContent(),
                article.getCreateTime(),
                article.getId());
    }

    //根据id查询一条记录
    public Article findById(Long id,JdbcTemplate jdbcTemplate){
        if(jdbcTemplate == null){
            jdbcTemplate = primaryJdbcTemplate;
        }
        return jdbcTemplate.queryForObject("select * from article where id = ?",new Object[]{id},new BeanPropertyRowMapper<>(Article.class));

    }

    //查询所有
    public List<Article> findAll(JdbcTemplate jdbcTemplate){
        if(jdbcTemplate == null){
            jdbcTemplate = primaryJdbcTemplate;
        }
        return jdbcTemplate.query("select * from article", new BeanPropertyRowMapper<>(Article.class));

    }









}
